package com.atguigu.juc.interview.lock;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 题目：请举例说明集合类是不安全的
 *      1.故障现象：
 *          java.util.ConcurrentModificationException
 *      2.导致原因：
 *      3.解决方案
 *          3.1   Vector
 *          3.2   Collections.synchronizedList(new ArrayList<>())
 *          3.3   CopyOnWriteArrayList
 *                      写时复制
 *      4.优化建议(同样的错误，不出现第2次)
 *
 *
 *
 * @author : leimingchao
 * @date Date : 2021年07月09日 22:35
 */
public class NotSafeDemo {

    public static void main(String[] args) {
        //listNoSafe();
        //setNoSafe();
        // Map<String,String> map = new HashMap<>();
        // Map<String,String> map = Collections.synchronizedMap(new HashMap<>());
        Map<String,String> map = new ConcurrentHashMap<>();
        for (int i = 1; i <= 30; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,8));
                System.out.println(map);
            },String.valueOf(i)).start();
        }

    }

    private static void setNoSafe() {
        // Set<String> set = new HashSet<>();
        // Set<String> set = Collections.synchronizedSet(new HashSet<>());
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 1; i <= 30; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }

    private static void listNoSafe() {
        // List<String> list = new ArrayList<>();
        // List<String> list = new Vector<>();
        List<String> list = new CopyOnWriteArrayList<>();
        // list.add("a");
        // list.add("b");
        // list.add("c");
        // list.forEach(System.out::println);
        for (int i = 1; i <= 30; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }
}
